package com.sinevil.tcpTrans.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sinevil.tcpTrans.entity.json.BasicJson;

import java.util.LinkedList;
import java.util.Stack;

/**
 * @Classname JsonReader
 * @Description Json读取器，用于解决粘包和拆包问题
 * @Version 1.0.0
 * @Date 2024/12/30 22:57
 * @Created by sinevil
 */
public class JsonReader {
    ObjectMapper objectMapper;
    Stack<Integer> symbolStack = new Stack<>();
    int begin = -1;
    int end = 0;
    JsonResult result = new JsonResult();
    StringBuilder stringBuffer = new StringBuilder(10240);


    public JsonReader(){
        this.objectMapper = new ObjectMapper();
    }

    public JsonReader(ObjectMapper objectMapper){
        this.objectMapper = objectMapper;
    }

    private LinkedList<BasicJson> findNextJson(StringBuilder buffer, int startIndex) {
        // 清空上次的结果
        this.result.jsons.clear();
        int symbol = 0;
        int maxIndex = buffer.length() - 1;
        for (int i = startIndex; i <= maxIndex; i++) {
            symbol = buffer.indexOf("%${j");
            if (symbol>=0)
                this.begin = symbol;
            symbol = buffer.indexOf("j}$%");
            if (this.begin != -1 && symbol>=0){
                try {
                    BasicJson jsonNode = objectMapper.readValue(buffer.substring(this.begin+4, symbol),BasicJson.class);
//                    System.out.println(jsonNode);
                    // 切除已处理的JSON字符串内容
                    buffer.delete(0, symbol+1);
                    // 更新下一次查找的起始位置为0，因为已经删除了前面处理过的部分
                    result.renew(jsonNode, 0);
                    i = 0;
                } catch (Exception e) {
                    // 括号匹配了但可能不是完整JSON，继续往后找
                }
            } else if (begin == -1) {
                // 损坏的数据包
                buffer.delete(0, symbol+1);
                this.begin = -1;
                result.nextStartIndex = 0;
            }
        }

        result.renew(null, !buffer.isEmpty() ? 0 : buffer.length() - 1);
        return result.jsons;
    }

    /**
     * 找到当前传入data中的所有完整JSON
     * @param data 要从中找寻JSON的字符串
     * @return JSON列表
     */
    public LinkedList<BasicJson> findNextJson(String data) {
        this.stringBuffer.append(data);
        return findNextJson(this.stringBuffer, result.nextStartIndex);
    }

    /**
     * 用于存储读取完整json过程中的信息
     */
    private class JsonResult {

        boolean hasJson;
        int nextStartIndex;

        LinkedList<BasicJson> jsons = new LinkedList<>();

        public JsonResult(){}
        public JsonResult(BasicJson json, int nextStartIndex) {
            this.jsons.push(json);
            this.nextStartIndex = nextStartIndex;
        }

        /**
         * 更新
         * @param json
         * @param nextStartIndex
         */
        public void renew(BasicJson json, int nextStartIndex){
            if (json!= null)
                this.jsons.push(json);

            this.nextStartIndex = nextStartIndex;

            /**
             * if (json != null)
             *     hasJson = true;
             * else hasJson=false;
             */
            hasJson = json != null;
        }
    }
}